#!/usr/bin/env python
# encoding: utf-8
'''
Created on Jun 6, 2011

@author: apple
'''

from flask import Module , render_template, request, session, redirect, url_for,flash

import usermodel as model
from usermodel import UserModel

user = Module(__name__ , name='user')

@user.route('/')
def index(info=''):
    if '_id' in session:
        user = model.getuser(session['_id'])
        return render_template('user/profile.html', user=user)
    return render_template('user/login.html')
    
@user.route('/register',methods = ['GET','POST'])
def register():
    if '_id' in session:
        return redirect(url_for('user.index'))
    if request.method == 'GET':
        return render_template('user/register.html')
    else:
        uid = request.form.get('email',None)
        passwd = request.form.get('passwd',None)
        agin   = request.form.get('agpwd',None)
        if not uid or not passwd or not agin:
            flash('Please input email and password.')
            return render_template('user/register.html')
        if passwd != agin:
            flash('Password error.')
            return render_template('user/register.html')
        result = model.setuser({'uid':uid,'passwd':passwd})
        if not result:
            flash('Uid error.')
            return render_template('user/reigster.html')
        session['_id'] = uid
        return redirect(url_for('user.index'))

@user.route('/questions')
def questions():
    if '_id' in session:
        user = model.getuser(session['_id'])
        questions = model.getuserquestions(session['_id'])
        return render_template('user/questions.html',user=user,questions=questions)
    return render_template('user/login.html')

@user.route('/answers')
def answers():
    if '_id' in session:
        user = model.getuser(session['_id'])
        questions = model.getuseranswers(session['_id'])
        return render_template('user/answers.html',user=user,questions=questions)
    return render_template('user/login.html')


@user.route('/login', methods=['POST', 'GET'])
@user.route('/login/<int:errorcode>', methods=['POST', 'GET'])
def login(errorcode=0):
    """
    login view
    param:@type int:errorcode <defined in user.config> 
    """
    if errorcode:
        return render_template('user/login.html')
    if '_id' in session:
        return redirect(url_for('user.index'))
    _id = request.form.get('email', '')
    passwd = request.form.get('passwd', '')
    if not _id or not passwd:
        return redirect(url_for('user.login', errorcode=1))
    result = model.login(_id, passwd)
    if result:
        n = request.args.get('next', '')
        nexturl = url_for('user.index') if not n else n
        session['_id'] = _id 
        return redirect(nexturl)
    else:
        return redirect(url_for('user.login' , errorcode=2))

@user.route('/logout' , methods=['POST', 'GET'])
def logout():
    session.pop('_id', None)
    return redirect(url_for('question.index'))
